// widgets/activation_dialog.dart
import 'package:flutter/material.dart';
import '../services/activation_service.dart';
import 'dart:io';

class ActivationDialog {
  static Future<bool> show({
    required BuildContext context,
    int maxAttempts = 3,
  }) async {
    int attempts = 0;
    final ActivationService activationService = ActivationService();
    
    while (attempts < maxAttempts) {
      final remainingAttempts = maxAttempts - attempts;
      final result = await _showActivationInputDialog(
        context, 
        remainingAttempts,
        attempts > 0, // 是否是重试
      );
      
      if (result == null) {
        // 用户点击取消
        return false;
      }
      
      if (result.success) {
        // 激活成功
        await _showSuccessDialog(context, result.expireTime!);
        return true;
      } else {
        // 激活失败
        attempts++;
        if (attempts >= maxAttempts) {
          await _showMaxAttemptsDialog(context);
          return false;
        } else {
          await _showErrorDialog(context, result.message!);
        }
      }
    }
    
    return false;
  }

  static Future<ActivationResult?> _showActivationInputDialog(
    BuildContext context, 
    int remainingAttempts,
    bool isRetry,
  ) async {
    final TextEditingController controller = TextEditingController();
    
    return await showDialog<ActivationResult>(
      context: context,
      barrierDismissible: false,
      builder: (context) => AlertDialog(
        title: Row(
          children: [
            Icon(Icons.vpn_key, color: Colors.deepPurple),
            SizedBox(width: 8),
            Text(isRetry ? '重新激活验证' : '激活验证'),
          ],
        ),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text('请输入激活码:'),
            SizedBox(height: 12),
            TextField(
              controller: controller,
              decoration: InputDecoration(
                hintText: '输入您的激活码',
                border: OutlineInputBorder(),
                prefixIcon: Icon(Icons.code),
              ),
              textInputAction: TextInputAction.done,
            ),
            SizedBox(height: 8),
            Text(
              '剩余尝试次数: $remainingAttempts',
              style: TextStyle(
                color: Colors.grey,
                fontSize: 12,
              ),
            ),
            if (isRetry) ...[
              SizedBox(height: 8),
              Text(
                '激活码格式示例: ACT123456789',
                style: TextStyle(
                  color: Colors.orange,
                  fontSize: 12,
                ),
              ),
            ],
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: Text('取消'),
          ),
          ElevatedButton(
            onPressed: () async {
              final code = controller.text.trim();
              if (code.isEmpty) {
                ScaffoldMessenger.of(context).showSnackBar(
                  SnackBar(content: Text('请输入激活码')),
                );
                return;
              }

              // 显示验证中
              final result = await showDialog<ActivationResult>(
                context: context,
                barrierDismissible: false,
                builder: (context) => FutureBuilder<ActivationResult>(
                  future: ActivationService().checkActivation(code),
                  builder: (context, snapshot) {
                    if (snapshot.connectionState == ConnectionState.waiting) {
                      return AlertDialog(
                        title: Text('验证中'),
                        content: Column(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            CircularProgressIndicator(),
                            SizedBox(height: 16),
                            Text('正在验证激活码...'),
                          ],
                        ),
                      );
                    }

                    if (snapshot.hasError) {
                      return AlertDialog(
                        title: Text('验证错误'),
                        content: Text('验证过程中发生错误'),
                        actions: [
                          TextButton(
                            onPressed: () => Navigator.of(context).pop(
                              ActivationResult(success: false, message: '验证错误'),
                            ),
                            child: Text('确定'),
                          ),
                        ],
                      );
                    }

                    final result = snapshot.data!;
                    return AlertDialog(
                      title: Text(result.success ? '验证成功' : '验证失败'),
                      content: Text(result.success 
                          ? '激活成功！到期时间: ${result.expireTime?.toString().split(' ')[0]}'
                          : result.message!),
                      actions: [
                        TextButton(
                          onPressed: () => Navigator.of(context).pop(result),
                          child: Text('确定'),
                        ),
                      ],
                    );
                  },
                ),
              );

              Navigator.of(context).pop(result);
            },
            child: Text('验证'),
          ),
        ],
      ),
    );
  }

  static Future<void> _showSuccessDialog(BuildContext context, DateTime expireTime) async {
    await showDialog(
      context: context,
      barrierDismissible: false,
      builder: (context) => AlertDialog(
        title: Row(
          children: [
            Icon(Icons.check_circle, color: Colors.green),
            SizedBox(width: 8),
            Text('激活成功'),
          ],
        ),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text('您的软件已成功激活！'),
            SizedBox(height: 8),
            Text(
              '到期时间: ${expireTime.toString().split(' ')[0]}',
              style: TextStyle(fontWeight: FontWeight.bold),
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: Text('开始使用'),
          ),
        ],
      ),
    );
  }

  static Future<void> _showErrorDialog(BuildContext context, String message) async {
    await showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Row(
          children: [
            Icon(Icons.error_outline, color: Colors.red),
            SizedBox(width: 8),
            Text('激活失败'),
          ],
        ),
        content: Text(message),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: Text('重试'),
          ),
        ],
      ),
    );
  }

  static Future<void> _showMaxAttemptsDialog(BuildContext context) async {
    await showDialog(
      context: context,
      barrierDismissible: false,
      builder: (context) => AlertDialog(
        title: Text('激活失败'),
        content: Text('超过最大尝试次数，程序将退出。'),
        actions: [
          TextButton(
            onPressed: () {
              Navigator.of(context).pop();
              exit(0);
            },
            child: Text('确定'),
          ),
        ],
      ),
    );
  }
}